package com.example.mapp.buildSql;

import com.example.ext.entity.ExtMessageNotice;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;
import java.util.Map;

/**
 * Created by simon on 2017/10/12.
 */
public class MessageNoticeMappSql {

    public String queryList(ExtMessageNotice extMessageNotice){

        String select = " DISTINCT t1.*, t5.party_name as sendUserName, t6.user_name as receiveUserName ";
        String table =" message_notice t1 " +
                "left join party_user t4 on t4.user_id=t1.send_user_id" +
                " left join party t5 on t5.id=t4.party_id " +
                " left join sys_user t6 on t1.receive_user_id=t6.id";
        String whereParam="";

        if(extMessageNotice.getIsRead()!=null && extMessageNotice.getIsRead().length()>0){
            whereParam+=" and t1.is_read = #{isRead}";
        }
        if(extMessageNotice.getCurrentUserId()!=null && extMessageNotice.getCurrentUserId().length()>0){
            whereParam+=" and t1.receive_user_id = #{currentUserId}";
        }
        if(extMessageNotice.getStartTime()!=null && extMessageNotice.getStartTime().length()>0){
            whereParam+=" and t1.notice_time > #{startTime}";
        }
        if(extMessageNotice.getEndTime()!=null && extMessageNotice.getEndTime().length()>0){
            whereParam+=" and t1.notice_time < #{endTime}";
        }

        String where = " 1=1 "+whereParam;
        String sql =  new SQL(){{
            SELECT(select);
            FROM(table);
            WHERE(where);
            ORDER_BY("t1.notice_time desc");
        }
        }.toString();

        int from = (extMessageNotice.getCurrentPage()-1)*extMessageNotice.getPageSize();
        String limit = " limit "+from+","+extMessageNotice.getPageSize();

        return sql+limit;
    }

    /**
     * 查询 发送列表
     * @param extMessageNotice
     * @return
     */
    public String querySendList(ExtMessageNotice extMessageNotice){

        String select = "t1.*, t5.user_name as sendUserName, t6.user_name as receiveUserName ";
        String table =" message_notice t1 " +
                " left join sys_user t5 on t5.id=t1.send_user_id " +
                " left join sys_user t6 on t1.receive_user_id=t6.id";
        String whereParam="";

        if(extMessageNotice.getIsRead()!=null && extMessageNotice.getIsRead().length()>0){
            whereParam+=" and t1.is_read = #{isRead}";
        }
        if(extMessageNotice.getCurrentUserId()!=null && extMessageNotice.getCurrentUserId().length()>0){
            whereParam+=" and t1.send_user_id = #{currentUserId}";
        }
        if(extMessageNotice.getStartTime()!=null && extMessageNotice.getStartTime().length()>0){
            whereParam+=" and t1.notice_time > #{startTime}";
        }
        if(extMessageNotice.getEndTime()!=null && extMessageNotice.getEndTime().length()>0){
            whereParam+=" and t1.notice_time < #{endTime}";
        }

        String where = " 1=1 "+whereParam;
        String sql =  new SQL(){{
            SELECT(select);
            FROM(table);
            WHERE(where);
            ORDER_BY("t1.notice_time desc");
        }}.toString();


        return sql;
    }

    public String countList(ExtMessageNotice extMessageNotice){

        String select = " count(t1.id)";
        String table =" message_notice t1 ";
        String whereParam="";

        if(extMessageNotice.getIsRead()!=null && extMessageNotice.getIsRead().length()>0){
            whereParam+=" and t1.is_read = #{isRead}";
        }
        if(extMessageNotice.getCurrentUserId()!=null && extMessageNotice.getCurrentUserId().length()>0){
            whereParam+=" and t1.receive_user_id = #{currentUserId}";
        }
        if(extMessageNotice.getStartTime()!=null && extMessageNotice.getStartTime().length()>0){
            whereParam+=" and t1.notice_time > #{startTime}";
        }
        if(extMessageNotice.getEndTime()!=null && extMessageNotice.getEndTime().length()>0){
            whereParam+=" and t1.notice_time < #{endTime}";
        }

        String where = " 1=1 "+whereParam;
        String sql =  new SQL(){{
            SELECT(select);
            FROM(table);
            WHERE(where);
        }
        }.toString();

        return sql;
    }

	public String findUserInfos(Map<String, Object> param) {

		String select = " DISTINCT sur.user_id,p.id party_id,b.register_id ";

		//判断是否是取直接下级还是，所有下级 （去除直接下级与所有下级的条件）
        StringBuilder builder = new StringBuilder();
//        if("1".equals(param.get("unitLevel"))){ //直接下级
//            builder.append(" party p left join (select id,party_name from party) pp on pp.id = p.parent_id " +
//                    "left join PARTY_USER PU ON PU.PARTY_ID = p.id " +
//                    "LEFT JOIN SYS_USER_ROLE SUR ON PU.USER_ID = SUR.USER_ID " +
//                    "LEFT JOIN SYSTEM_ROLE SR ON SUR.role_id = SR.id " +
//                    "LEFT JOIN user_reg_id b ON sur.user_id = b.user_id ");
//        }else {
//            builder.append(" SUB_PARTY_INFO p  " + "LEFT JOIN PARTY_USER PU ON PU.PARTY_ID = p.ID   "
//                    + "LEFT JOIN SYS_USER_ROLE SUR ON PU.USER_ID = SUR.USER_ID "
//                    + "LEFT JOIN SYSTEM_ROLE SR ON SUR.role_id = SR.id  "
//                    + "LEFT JOIN user_reg_id b ON sur.user_id = b.user_id ");
//        }
        builder.append(" SUB_PARTY_INFO p  " + "LEFT JOIN PARTY_USER PU ON PU.PARTY_ID = p.ID   "
                + "LEFT JOIN SYS_USER_ROLE SUR ON PU.USER_ID = SUR.USER_ID "
                + "LEFT JOIN SYSTEM_ROLE SR ON SUR.role_id = SR.id  "
                + "LEFT JOIN user_reg_id b ON sur.user_id = b.user_id ");

        String table = builder.toString();
		String whereParam = "";
        whereParam += " and p.parent_id=#{id} ";

		if(param.get("partyType") != null && (param.get("partyType") + "").length() > 0 && !"0".equals(param.get("partyType"))){ //选择的单位类型
            whereParam += " and P.PARTY_TYPE = #{partyType}";
        }
		//获取单位集合
        List<Integer> partyIds = (List<Integer>) param.get("partyIds");
		if(!"0".equals(param.get("partyType")) && partyIds != null && partyIds.size() > 0){
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < partyIds.size(); i++) {
                if ("".equals(str.toString())) {
                    str.append("(#{partyIds["+i+"]}");
                } else {
                    str.append(", #{partyIds["+i+"]}");
                }
            }
            str.append(")");
            whereParam += " and p.id in "+str.toString();
        }


        /**
         * 添加用户类型的集合
         */
        List<String> userTypeIds = (List<String>) param.get("userTypes");
        if(userTypeIds != null && userTypeIds.size() > 0){
            StringBuilder builder1 = new StringBuilder(" and SR.id in ( ");
            for (int i = 0; i < userTypeIds.size(); i++) {
                String userTypeId = String.valueOf(userTypeIds.get(i));
                if (i == userTypeIds.size() - 1) {
                    builder1.append("'").append(userTypeId).append("'");
                } else {
                    builder1.append("'").append(userTypeId).append("',");
                }
            }
            whereParam += builder1.append(")").toString();
        }

        // 获取用户id
        List<String> userIdList =(List<String>) param.get("userIdList");
        if(userIdList !=null && userIdList.size()>0){
            StringBuilder builder2 = new StringBuilder(" and SUR.user_id in ( ");
            // 进行In拼接
            for (int i = 0; i < userIdList.size(); i++) {
                String userId = String.valueOf(userIdList.get(i));
                if (i == userIdList.size() - 1) {
                    builder2.append("'").append(userId).append("'");
                } else {
                    builder2.append("'").append(userId).append("',");
                }
            }
            whereParam += builder2.append(")").toString();
        }

        String where = " 1=1 " + whereParam;
		String sql = new SQL() {
			{
				SELECT(select);
				FROM(table);
				WHERE(where);
			}
		}.toString();
		return sql;
	}
}
